package br.com.poc.pitagorasnumero.model.bo.impl;

import java.util.ArrayList;
import java.util.List;

import br.com.poc.pitagorasnumero.model.bo.IHouseBO;
import br.com.poc.pitagorasnumero.type.TablePitagoricaType;
import br.com.poc.pitagorasnumero.util.ExpressionNumberPitagoras;
import br.com.poc.pitagorasnumero.util.StringUtil;

/**
 * The Class HouseBO.
 * 
 * @author irlan.gomes
 */
public class HouseBO implements IHouseBO {

	/** The calculation manager. */
	private static CalculationNumberManager calcManager;

	static {
		calcManager = new CalculationNumberManager();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.poc.pitagorasnumero.model.bo.IHouseBO#doHouseEnergy(java.lang.
	 * String)
	 */
	/** {@inheritDoc} **/
	@Override
	public int doHouseEnergy(final String numberHouse) {

		final String nameValidated = calcManager.validateName(numberHouse);

		final String[] number = ExpressionNumberPitagoras
				.getOnlyNumber(nameValidated);

		final String[] letter = ExpressionNumberPitagoras
				.getOnlyLetter(nameValidated);

		final List<TablePitagoricaType> parseLetter = convertLetterNumber(
				number, letter);

		final int sumLetter = calcManager.sumLetter(parseLetter);

		final int reduceNumberMagic = calcManager.reduceNumberMagic(sumLetter);

		return reduceNumberMagic;
	}

	/**
	 * Convert letter number.
	 * 
	 * @param number
	 *            the number
	 * @param letter
	 *            the letter
	 * @return the list
	 */
	private List<TablePitagoricaType> convertLetterNumber(
			final String[] number, final String[] letter) {
		final List<TablePitagoricaType> parseLetter = new ArrayList<TablePitagoricaType>();
		parseLetter.addAll(convertLetterNumber(number));
		parseLetter.addAll(calcManager.convertLetterNumber(letter));
		return parseLetter;
	}

	/**
	 * Convert letter number.
	 * 
	 * @param number
	 *            the number
	 * @return the list
	 */
	private List<TablePitagoricaType> convertLetterNumber(final String[] number) {

		final List<TablePitagoricaType> tablePitagList = new ArrayList<TablePitagoricaType>();

		for (int i = 0; i < number.length; i++) {

			if (StringUtil.notEmpty(number[i])) {

				final int numberItem = Integer.parseInt(number[i]);

				final TablePitagoricaType valueLetter = TablePitagoricaType
						.getValueNumber(numberItem);

				tablePitagList.add(valueLetter);
			}

		}

		return tablePitagList;
	}

}
